package demo.validation.group;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

// 用于验证学生信息的控制器
@Controller
public class ValidateGroupStudentController {
    @GetMapping("/validate-group")
    public String addUser(Model model) {
        model.addAttribute("student", new Student());
        return "validation/group-student";
    }

    @PostMapping("/validate-group-create")
    public String addUser(@Validated( { Student.Create.class }) @ModelAttribute("student") Student s, BindingResult bindingResult) {
        for (var v : bindingResult.getFieldErrors()) {
            System.out.println(v.getField()+  " = " + v.getDefaultMessage());
        }
        if (bindingResult.hasErrors()) {
            return "validation/group-student";
        }
        return "validation/detail";
    }

    @PostMapping("/validate-group-edit")
    public String editUser(@Validated( { Student.Update.class }) @ModelAttribute("student") Student s, BindingResult bindingResult) {
        for (var v : bindingResult.getFieldErrors()) {
            System.out.println(v.getField()+  " = " + v.getDefaultMessage());
        }
        if (bindingResult.hasErrors()) {
            return "validation/group-student";
        }
        return "validation/detail";
    }
}
